import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 状态码200进入
    const { success, data, message } = response.data
    if (success) {
      return data
    } else {
      Message({
        message: message,
        type: 'error',
        duration: 5 * 1000
      })
      // 抛出一个promise 错误
      return Promise.reject(new Error(message))
    }
  },
  error => {
    // 出错：状态码400 及以上执行(请求没有发出)
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

// // 导出一个axios的实例  而且这个实例要有请求拦截器 响应拦截器
// import axios from 'axios'
// // 创建了一个新的axios实例
// const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   timeout: 5000 // 超时时间
// })
// service.interceptors.request.use() // 请求拦截器
// service.interceptors.response.use(response => { // 从axios的data中解构出来必要的字段
//   const { success, message, data } = response.data
//   // 如果success为true,直接返回data即可
//   if (success) {
//     return data
//   } else {
//     // 如果success为false 业务出错,直接触发reject 组件调用接口可通过try/catch捕获错误
//     return Promise.reject(new Error(message))
//   }
// }, error => {
//   return Promise.reject(error) // 返回执行错误 让当前的执行链进入 catch
// }) // 响应拦截器
// export default service // 导出axios实例
